package com.jsb.laundry.controller;

import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.constant.CommonConstants;
import com.jsb.laundry.common.enums.OrderStatus;
import com.jsb.laundry.common.mq.WaitPayConfig;
import com.jsb.laundry.common.mq.confirm_receive_deadLetter.UserConfirmReceiveOrderConfig;
import com.jsb.laundry.common.response.WebResponse;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.http.HttpUtil;
import com.jsb.laundry.dao.OrderDao;
import com.jsb.laundry.model.entity.JsbOrders;
import com.jsb.laundry.model.vo.PrePayVo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/mq")
public class MQController {
    private static final Logger LOGGER = LoggerFactory.getLogger(MQController.class);

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private OrderDao orderDao;

    /**
     * 骑手确认送达,投递消息 (orderId)
     *
     * @param orderInfo
     */
    @PostMapping("/riderConfirmedDelivery")
    public WebResponse sendMsg(@RequestBody PrePayVo orderInfo) {
        if (JSBUtil.isEmptyString(orderInfo.getOrderId())) {
            return WebResponse.failOfParameter();
        }
        orderInfo.setTrigger("rider");

        rabbitTemplate.convertAndSend(UserConfirmReceiveOrderConfig.userConfirmReceiveOrderExchange,
                UserConfirmReceiveOrderConfig.userConfirmReceiveOrderRoutingKey, orderInfo,
                msg -> {
                    //发送消息的时候的延迟时长
//                    msg.getMessageProperties().setExpiration(String.valueOf(1000 * 60 * 5));
                    msg.getMessageProperties().setExpiration(String.valueOf(UserConfirmReceiveOrderConfig.autoReceiveOrderTime));
                    return msg;
                });
        LOGGER.info("骑手确认送达给用户,7天后该订单自动收货,入参：{}", orderInfo);
        return WebResponse.success();
    }


    /**
     * 用户主动 消费消息
     *
     * @param orderInfoVo
     */
    @PostMapping("/userConsumerMsg")
    public WebResponse userConsumerMsg(@RequestBody PrePayVo orderInfoVo) {
        if (JSBUtil.isEmptyString(orderInfoVo.getOrderId())) {
            return WebResponse.failOfParameter();
        }
        orderInfoVo.setTrigger("rider");
        String orderId = orderInfoVo.getOrderId();

//        Object o = rabbitTemplate.convertSendAndReceive(UserConfirmReceiveOrderConfig.userConfirmReceiveOrderExchange,
//                UserConfirmReceiveOrderConfig.userConfirmReceiveOrderRoutingKey, orderInfoVo, message -> {
//                    //发送消息的时候的延迟时长
//                    message.getMessageProperties().setExpiration(String.valueOf(0));
//                    return message;
//                });

        JsbOrders orderInfo = orderDao.getOrderInfo(orderId);
        /**
         *  1.订单未被接收促发系统分账
         *  2.添加jsb_order_status_log记录
         *  3.填充jsb_orders时间success_at
         */
        if (orderInfo != null && JSBUtil.isEmptyObject(orderInfo.getSuccessAt())) {
            int var0 = orderDao.updParentOrderSuccessAt(orderId);
            int var1 = orderDao.addOrderStatusLog(orderId, OrderStatus.ORDER_SUCCESS.getCode(), "7天后系统自动确认收货", "2");
            /**
             * TODO 系统分账
             */
            Map<String,String> map = new HashMap();
            map.put("orderId",orderId);
            String res = HttpUtil.sendPost("http://127.0.0.1:20000/riderOrder/qs/splitSettled", null, JSONObject.toJSONString(map));


            log.info("更新jsb_orders时间success_at:【入参:{},出参:{}】", orderId, var0);
            log.info("添加jsb_order_status_log记录:【入参:{},{},{},{},出参:{}】", orderId, OrderStatus.ORDER_SUCCESS.getCode(), "7天后系统自动确认收货", "2", var1);
            log.info("促发系统分账:【入参:{},出参:{}】", orderId, res);
        }

        LOGGER.info("用户主动在7天内收货,入参：{}", orderInfo);
        return WebResponse.success();
    }

}
